package omq.panel;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.net.URL;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import omq.api.OMQConnectionFactory;
import omq.api.OMQConnectionSOAP;
import omq.api.OMQMessage;
import omq.api.OMQQueue;
import omq.api.OMQQueueManager;
import omq.api.logger.OMQLogger;
import omq.file.OMQFile;
import omq.screen.DefaultScreen;
import omq.screen.OmqTesterMainScreen;
import omq.xml.OMQXmlUtil;

import component.OmqButton;
import component.OmqRadioButton;

import constant.OmqTesterClientConst;

public class SendMsgPanel extends OmqPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3135141456996244116L;
	private static final String FILE = "File";
	private static final String StringOBJECT = "String";
	private JTextField message;
	private OmqButton put;
	private ButtonGroup sendObjectBtnGrp;
	private JButton fcChooseBtn;
	private JLabel fcPathLbl;
	private JFileChooser fc ;
	protected File fileToSend;

	OmqRadioButton sendFile ;
	OmqRadioButton sendObject ;
	
	public SendMsgPanel(LayoutManager arg0, boolean arg1) {
		super(arg0, arg1);
		initialize();
	}

	public SendMsgPanel(LayoutManager arg0) {
		super(arg0);
		initialize();
	}

	public SendMsgPanel(boolean arg0) {
		super(arg0);
		initialize();
	}

	public SendMsgPanel() {
		super();
		initialize();
	}
	
	private void initialize(){
		setLayout(new GridLayout(0,1));
		
		getInfoLbl().setText("<html><body>" + getTitle("Send (PUT) message") +"Choose the message type you wish to send and press the 'Send' button.</body></html>");
		sendObjectBtnGrp = new ButtonGroup();
		URL imagesurl = SendMsgPanel.class.getResource("../../images/");
		sendObject = new OmqRadioButton("<html><body><table><tr><td align='center' valign='middle'>Send text message &nbsp;</td><td> <img src='"+imagesurl+"/sendObject.png'  border=0></td></tr></table></body></html>");
		sendObject.setActionCommand(StringOBJECT);
		sendFile = new OmqRadioButton("<html><body><table><tr><td align='center' valign='middle'>Send XML file &nbsp;</td><td> <img src='"+imagesurl+"/sendFile.png'  border=0></td></tr></table></body></html>");
		sendFile.setActionCommand(FILE);
		sendObject.setSelected(true);
		sendObjectBtnGrp.add(sendFile);
		sendObjectBtnGrp.add(sendObject);
		//1
		add(getInfoLbl());
		//2
		add(sendObject);
		OmqPanel textPnl = new OmqPanel();
		textPnl.add(getMessage());
		add(textPnl);
		//3
		add(sendFile);
		OmqPanel filechooserPnl = new OmqPanel();
		fc = new JFileChooser();
		filechooserPnl.setSize(new Dimension(150,21));
		filechooserPnl.add(getFcChooseBtn());
		filechooserPnl.add(getFcPathLbl());
		add(filechooserPnl);
		
		//4)Adding the put button to the main anel
		//Put button panel - holds only the put button.
		OmqPanel putPanel = new OmqPanel();
		putPanel.setSize(new Dimension(120,35));
		putPanel.add(getPut());
		add(putPanel);
		initpref();
	}

	public JTextField getMessage() {
		if (message == null){
			message = new JTextField();
			message.setPreferredSize(new Dimension(450,21));
			message.setMaximumSize(new Dimension(450,21));
			message.addFocusListener(new FocusListener() {
			
				public void focusLost(FocusEvent arg0) {
					OMQLogger.getInstance().debug("Lost focus.");
				}
			
				public void focusGained(FocusEvent arg0) {
					if(!sendObject.isSelected()){
						sendObject.setSelected(true);
					}
				}
			
			});
		}
		return message;
	}

	public OmqButton getPut() {
		if(put == null){
			put = new OmqButton("  Send",DefaultScreen.createImageIcon("../../images/save.png","Send to queue"));
			put.setSize(new Dimension(120,35));
			put.setPreferredSize(new Dimension(120,35));
			put.setMaximumSize(new Dimension(120,35));
			put.addActionListener(new ActionListener() {
			
				public void actionPerformed(ActionEvent a) {
					boolean goon= true;
					OMQLogger.getInstance().info("send message request is launched");
					
					String action = sendObjectBtnGrp.getSelection().getActionCommand();
					
					OMQLogger.getInstance().debug("object type = "+action);
					

					// if no string is entered or no file is selected - propmpt
					// an error message
					if(action.equals(StringOBJECT))
					{
						if ((getMessage().getText()).length() == 0)
						{
							OMQLogger.getInstance().info("cannot send an empty string");			
							JOptionPane.showMessageDialog(new JFrame(),"<html><body>cannot send an empty string</body></html>","Message",JOptionPane.ERROR_MESSAGE);
							goon = false;
						}
					}
					if(action.equals(FILE))
					{
						if (fileToSend == null)
						{
							OMQLogger.getInstance().info("no file was selected");			
							JOptionPane.showMessageDialog(new JFrame(),"<html><body>no file was selected</body></html>","Message",JOptionPane.ERROR_MESSAGE);
							goon = false;
						}
					}
					
					// sending the message
					if (goon)
					{
						{JOptionPane.showMessageDialog(new JFrame(),"<html><body>Sending message, please wait ...</body></html>","Message",JOptionPane.INFORMATION_MESSAGE);
						waitForInfo(true);
						
						HashMap pref = OmqTesterMainScreen.prefMap;
						
						try {

							conn = OMQConnectionFactory.getConnection(myPreferences.get(OmqTesterClientConst.PREF_USER_NAME, OmqTesterClientConst.PREF_USER_NAME),
									myPreferences.get(OmqTesterClientConst.PREF_PASSWORD, OmqTesterClientConst.PREF_PASSWORD),
									myPreferences.get(OmqTesterClientConst.PREF_SERVER_URL, OmqTesterClientConst.PREF_SERVER_URL),
									new OMQQueueManager(myPreferences.get(OmqTesterClientConst.PREF_QUEUE_MGR, OmqTesterClientConst.PREF_QUEUE_MGR)));

							OMQLogger.getInstance().info("user      = "+myPreferences.get(OmqTesterClientConst.PREF_USER_NAME, OmqTesterClientConst.PREF_USER_NAME));						
							OMQLogger.getInstance().info("qmgr      = "+myPreferences.get(OmqTesterClientConst.PREF_QUEUE_MGR,OmqTesterClientConst.PREF_QUEUE_MGR));						
							OMQLogger.getInstance().info("queue     = "+myPreferences.get(OmqTesterClientConst.PREF_QUEUE_NAME,OmqTesterClientConst.PREF_QUEUE_NAME));						
							OMQLogger.getInstance().info("server    = "+myPreferences.get(OmqTesterClientConst.PREF_SERVER_URL,OmqTesterClientConst.PREF_SERVER_URL));
							
							sess = conn.createSession(false);
							
							OMQMessage msg = null;
							
							if(action.equals(FILE))
							{
								OMQLogger.getInstance().info("about to send file named : "+fileToSend.getName()+", please wait");
								OMQFile fileMessage = new OMQFile();
								fileMessage.setOmqFileContent(OMQXmlUtil.getBytesFromFile(fileToSend));
								fileMessage.setOmqFileName(fileToSend.getName());
								msg = new OMQMessage(fileMessage);
//								pref.put("message",OMQConversions.Object2Base64(fileMessage));
							}
							else if(action.equals(StringOBJECT))
							{
								OMQLogger.getInstance().info("about to send the string : "+getMessage().getText()+", please wait");
								
								msg = new OMQMessage(getMessage().getText().getBytes("UTF-8"));
//								pref.put("message",OMQConversions.Object2Base64(getMessage().getText()));
							}

							int rc = sess.sendMessage(new OMQQueue(myPreferences.get(OmqTesterClientConst.PREF_QUEUE_NAME,OmqTesterClientConst.PREF_QUEUE_NAME)), msg);
							
							if(rc == 0){
								OMQLogger.getInstance().info("message sent succesfully, msgid = "+sess.getLastMessageID());
								JOptionPane.showMessageDialog(new JFrame(),"<html><body>The message sent to the queue " + myPreferences.get(OmqTesterClientConst.PREF_QUEUE_NAME,OmqTesterClientConst.PREF_QUEUE_NAME) + " with message ID : " + sess.getLastMessageID() + "</body></html>","Message sent",JOptionPane.INFORMATION_MESSAGE);
							}else{
								OMQLogger.getInstance().info("send message failed, rc = "+sess.getLastErrorCode()+" error description = "+sess.getLastErrorDescription());
								String response = printErrorFromOMQ("Send message", false);
								JOptionPane.showMessageDialog(new JFrame(),response,"Send message error",JOptionPane.WARNING_MESSAGE);
							}
						} catch (Exception e) {
							OMQLogger.getInstance().error(e.getMessage());
							JOptionPane.showMessageDialog(new JFrame(),"<html><body>" + e.getMessage() + "</body></html>","System error",JOptionPane.ERROR_MESSAGE);
							waitForInfo(false);
						}
					}
					waitForInfo(false);
				}
				}});
		}
		return put;
	}

	public JButton getFcChooseBtn() {
		if(fcChooseBtn == null){
			fcChooseBtn = new JButton("Choose");
			fcChooseBtn.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					if(!sendFile.isSelected()){
						sendFile.setSelected(true);
					}
					int returnVal = fc.showOpenDialog(SendMsgPanel.this);
		            if (returnVal == JFileChooser.APPROVE_OPTION) {
		            	fileToSend = fc.getSelectedFile();
		            	
		                //This is where a real application would open the file.
		            	String pathUI;
		            	if(fileToSend.getAbsolutePath().length() > 80){
		            		pathUI = fileToSend.getAbsolutePath().substring(0,75) + "...";
		            	}else{
		            		pathUI = fileToSend.getAbsolutePath();
		            	}
		            	getFcPathLbl().setText( pathUI);
		            } else {
		            	getFcPathLbl().setText("Command cancelled by user.");
		            }
				}
			});
		}
		return fcChooseBtn;
	}

	public JLabel getFcPathLbl() {
		if(fcPathLbl== null){
			fcPathLbl = new JLabel("<html><body>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</body></html>");
			fcPathLbl.setBorder(BorderFactory.createTitledBorder("Chosen file"));
			fcPathLbl.setPreferredSize(new Dimension(350,35));
		}
		return fcPathLbl;
	}

	public void resetPanel(){
		getFcPathLbl().setText("");
		getMessage().setText("");
		sendObject.setSelected(true);
		fileToSend = null;
	}
}
